//
//  PicturePickerController.swift
//  Weibo8023
//
//  Created by styshy on 15/12/19.
//  Copyright © 2015年 sz. All rights reserved.
//

import UIKit

private let PicturePickerCellId = "PicturePickerCellId"

private let PicturePickerMaxCount = 3

class PicturePickerController: UICollectionViewController {
    
    // 配图数组
    lazy var pictures = [UIImage]()
    
    private var selecteIndex = 0
    
    // 构造函数
    init() {
        // 自定义一个Layout
        super.init(collectionViewLayout: PicturePickerLayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置背景颜色
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        
        collectionView?.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: PicturePickerCellId)
    }
    
    
    private class PicturePickerLayout:UICollectionViewFlowLayout{
        // 重写prepareLayout方法
        private override func prepareLayout() {
            super.prepareLayout()
            
            let count:CGFloat = 4
            let margin = UIScreen.mainScreen().scale * 4
            let w = (collectionView!.bounds.width - (count + 1) * margin ) / count
            
            itemSize = CGSize(width: w, height: w)
            
            sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
            
            minimumLineSpacing = margin
            minimumInteritemSpacing = margin
        }
    }

}

// MARK: - 代理方法的实现
extension PicturePickerController{
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        return pictures.count + (pictures.count == PicturePickerMaxCount ? 0 : 1)
        return pictures.count + 1
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PicturePickerCellId, forIndexPath: indexPath) as! PicturePickerCell
        
        cell.pictureDelegate = self
        
//        cell.image = (indexPath.item < pictures.count) ? pictures[indexPath.item] : nil
        if indexPath.item == pictures.count{
            cell.image = nil
            return cell
        }
        
        cell.image = pictures[indexPath.item]

        
        return cell
    }
}


// MARK: - PicturePickerCellDelegate 代理
extension PicturePickerController:PicturePickerCellDelegate{
    @objc private func picturePickerCellDidAdd(cell: PicturePickerCell) {
        print("添加图片")
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            print("无法访问照片库")
            return
        }
        
        selecteIndex = collectionView?.indexPathForCell(cell)?.item ?? 0
        
        let picker = UIImagePickerController()
        
        picker.delegate = self
        
        self.presentViewController(picker, animated: true, completion: nil)
    }
    
    @objc private func picturePickerCellDidRemove(cell: PicturePickerCell) {
        let indexPath = collectionView!.indexPathForCell(cell)!
        
        if indexPath.item >= pictures.count{
            return
        }
        
        pictures.removeAtIndex(indexPath.item)
        
//        collectionView?.deleteItemsAtIndexPaths([indexPath])
        collectionView?.reloadData()
        
    }
}

// MARK: - 相册的代理方法
extension PicturePickerController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        print(info)
        // 获取图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        // 获取缩放后的图片
        let scaleImage = image.scaleToWidth(600)
        
        if selecteIndex >= pictures.count{
            pictures.append(scaleImage)
        }else{
            pictures[selecteIndex] = scaleImage
        }
        
        collectionView?.reloadData()
        
        // 刷新控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
}


@objc
private protocol PicturePickerCellDelegate:NSObjectProtocol{
    
    optional func picturePickerCellDidAdd(cell:PicturePickerCell)
    
    optional func picturePickerCellDidRemove(cell:PicturePickerCell)
}


/// 自定义CollectionView的cell
private class PicturePickerCell:UICollectionViewCell{
    
    weak var pictureDelegate:PicturePickerCellDelegate?
    
    var image:UIImage?{
        didSet{
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal)
            
            removeButton.hidden = (image == nil)
        }
    }
    
    // 添加图片
    @objc func addPicture(){

        pictureDelegate?.picturePickerCellDidAdd?(self)
    }
    // 删除图片
    @objc func removePicture(){

        pictureDelegate?.picturePickerCellDidRemove?(self)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 设置布局
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI(){
        addSubview(addButton)
        addSubview(removeButton)
        
        
        // 添加监听 方法
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside)
        
        addButton.frame = bounds
        
        removeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.right.equalTo(self.snp_right)
        }
        
        addButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
    }
    
    
    // 懒加载孔家
    private lazy var addButton:UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    
    private lazy var removeButton:UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
    
}
